package cn.itsource.order.controller;


import cn.itsource.basic.constant.AlipayConfig;
import cn.itsource.order.domain.AlipayInfo;
import cn.itsource.order.service.IAlipayInfoService;
import cn.itsource.order.service.IPayBillService;
import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

@Controller
@RequestMapping("/alipay")
public class AlipayController {

    @Autowired
    private IAlipayInfoService alipayInfoService;

    @Autowired
    private IPayBillService payBillService;

    @RequestMapping("/returnUrl")
    public String returnUrl(HttpServletRequest request){
        try {
            //获取支付宝GET过来反馈信息
            Map<String,String> params = new HashMap<String,String>();
            //获取url地址携带的所有参数(它是把参数封装成一个map集合了)
            Map<String,String[]> requestParams = request.getParameterMap();
            //获取所有的key值，并且对key进行循环迭代
            for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
                //拿到key值
                String name = (String) iter.next();
                //通过key值，获取对应的value
                String[] values = (String[]) requestParams.get(name);
                String valueStr = "";
                for (int i = 0; i < values.length;  i++) {
                    valueStr = (i == values.length - 1) ? valueStr + values[i]
                            : valueStr + values[i] + ",";
                }
                params.put(name, valueStr);
            }
            //获取appid
            String app_id = params.get("app_id");
            //通过appid获取支付信息对象
            AlipayInfo alipayInfo = alipayInfoService.findByAppid(app_id);
            //验签
            //调用SDK验证签名
            boolean signVerified = AlipaySignature.rsaCheckV1(params, alipayInfo.getAlipay_public_key(), AlipayConfig.charset, AlipayConfig.sign_type);
            //——请在这里编写您的程序（以下代码仅作参考）——
            if(signVerified) {//验签成功
                return "redirect:http://localhost:8082/success.html";
            }
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        return "redirect:http://localhost:8082/error.html";

    }

    @RequestMapping("/notifyUrl")
    @ResponseBody
    public String notifyUrl(HttpServletRequest request){
        try {
            //获取支付宝POST过来反馈信息
            Map<String,String> params = new HashMap<String,String>();
            Map<String,String[]> requestParams = request.getParameterMap();
            for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
                String name = (String) iter.next();
                String[] values = (String[]) requestParams.get(name);
                String valueStr = "";
                for (int i = 0; i < values.length; i++) {
                    valueStr = (i == values.length - 1) ? valueStr + values[i]
                            : valueStr + values[i] + ",";
                }
                params.put(name, valueStr);
            }
            //获取appid
            String app_id = params.get("app_id");
            //通过appid获取支付信息对象
            AlipayInfo alipayInfo = alipayInfoService.findByAppid(app_id);
            //验签
            boolean  signVerified = AlipaySignature.rsaCheckV1(params, alipayInfo.getAlipay_public_key(), AlipayConfig.charset, AlipayConfig.sign_type);
            if(signVerified) {//验证成功
                //订单号
                String out_trade_no = request.getParameter("out_trade_no");
                //支付宝交易号
                String trade_no = request.getParameter("trade_no");
                //交易状态
                String trade_status = request.getParameter("trade_status");

                //交易成功
                if(trade_status.equals("TRADE_SUCCESS")){
                    //处理订单
                    payBillService.handleOrder(out_trade_no, trade_no);
                    //交易成功就返回success
                    return "success";
                }
            }
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        //交易失败
        return "failure";
    }
}
